package models

import (
	"gorm.io/gorm"
	"mishop/utils"
)

type User struct {
	gorm.Model
	Name     string   `json:"name"`
	Phone    string   `json:"phone"`
	Openid   string   `json:"openid"`
	Avatar   string   `json:"avatar"`
	Sex      uint8    `json:"sex"`
	Password string   `json:"password"`
	Token    string   `json:"token"`
	db       *gorm.DB `json:"-"`
}

func (p *User) FindByOpenid(openid string) (user *User, err error) {
	user = &User{Openid: openid}
	result := p.db.Where("openid = ?",openid).First(user)
	err = result.Error
	return
}

func (p *User) Create(u *User) (user *User, err error) {
	user = &User{Openid: u.Openid,Phone: u.Phone ,Token: utils.GenerateUserToken()}
	result := p.db.Create(user)
	err = result.Error
	return user, err
}

func (User) TableName() string {
	return "users"
}
func (p *User) FindByID(product_id uint) (model *User, err error) {
	model = &User{}
	result := p.db.First(model)
	err = result.Error
	return
}

func (p User) FindByUserID(page, rows int, category_id uint) (pages Pages, error error) {
	panic("implement me")
}

type IUser interface {
	FindByID(product_id uint) (*User, error)
	FindByUserID(page, rows int, category_id uint) (pages Pages, error error)
	FindByOpenid(openid string) (*User, error)
	Create(u *User) (*User, error)
}

func NewUser(db *gorm.DB) IUser {
	return &User{db: db}
}
